#! /usr/bin/env python3
import os
import sys
import json
sys.path.append(os.path.dirname(__file__))
import cgi
import mainWeb
import searchWeb
import getNewWeb
import loginWeb
_PLATFORM = "win" in sys.platform and "windows" or "linux"
import cgitb
cgitb.enable()


def get_config(path="config.json"):
    with open(path, "r+", encoding="utf-8") as f:
        json_dict = json.load(f)
        return json_dict


def login():
    config = get_config()
    note_path = config.get("note_path", {}).get(_PLATFORM, None)
    except_list = config.get("except_list", None)
    loginWeb.main(note_path, except_list)


def index():
    config = get_config()
    note_path = config.get("note_path", {}).get(_PLATFORM, None)
    except_list = config.get("except_list", None)
    mainWeb.main(note_path, except_list)


def search():
    config = get_config()
    note_path = config.get("note_path", {}).get(_PLATFORM, None)
    except_list = config.get("except_list", None)
    searchWeb.main(note_path=note_path, except_list=except_list, execf="searchWeb.py")


def newWeb():
    config = get_config()
    note_path = config.get("note_path", {}).get(_PLATFORM, None)
    except_list = config.get("except_list", None)
    getNewWeb.main(note_path, except_list, "markdownWeb.py")


if __name__ == "__main__":
    config = get_config()
    cgi_mod = cgi.FieldStorage()
    label = cgi_mod.getvalue('label')
    pass_list = config.get("passwd", None)
    states = False
    try:
        cookies = os.getenv("HTTP_COOKIE")
        exec(cookies)
        if state in pass_list:
            states = True
    except Exception:
        pass

    if label == 'index':
        if states is False:
            login()
        else:
            index()
    if label == 'search':
        if states is False:
            login()
        else:
            search()
    if label == 'new':
        if states is False:
            login()
        else:
            newWeb()
    elif not label:
        if states is False:
            login()
        else:
            index()
